package cn.b.sky.form.form.builder.impl;

import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.form.form.builder.BaseElementBuilder;
import cn.b.sky.form.model.BusinessAttachment;
import cn.b.sky.form.model.BusinessField;
import cn.b.sky.form.model.ScreenField;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

public class FileUploadBuilder extends BaseElementBuilder {

  @Override
  protected String buildHtmlElement(ScreenField sf) {
    BusinessField field = sf.getBf();
    int fileSize = field.getAttachments() == null ? 0 : field.getAttachments().size();
    StringBuilder sb = new StringBuilder();
    if (sf.getReadonlyFlag() != 1) {
      sb.append(" <div style=\"float: left;\">");
      sb.append("<input id=\"input_{fieldId}\" type=\"file\" uploaderOption=\"{");
      sb.append("swf: '{servletPath}/styles/uploadify/scripts/uploadify.swf',");
      sb.append("uploader: '{servletPath}/manage/businessAttach/saveAttachment;jsessionid={sessionid}',");
      sb.append("fileTypeDesc: 'All Files',");
      sb.append("fileTypeExts: '*.*', ");
      sb.append("buttonClass: 'my-uploadify',");
      sb.append("width: 61,");
      sb.append("height: 24,");
      sb.append("auto: false,"); //自动上传
      sb.append("buttonText: '选择文件',");
      sb.append("multi: false,");
      sb.append("onUploadSuccess: {fieldId}Attachment.uploadSuccess");
      sb.append("}\"");
      sb.append(" name=\"").append(field.getDbField()).append("\"");
      sb.append(" />");
      sb.append("</div>");
      sb.append("<div class=\"buttonActive\" style=\"float: right;\"><div class=\"buttonContent\"><button type=\"button\" onclick=\"{fieldId}Attachment._uploadFile();\">上传</button></div></div>");
      sb.append(getFileScriptStr(fileSize));
    }
    sb.append("<div id=\"div_{fieldId}\" class=\"fileQueue\">");
    //填充附件，附件回显
    if (field.getAttachments() != null) {
      sb.append(getAttachmentList(field.getAttachments(),sf.getReadonlyFlag()));
    }
    sb.append("</div>");
    String fileHtml = sb.toString();
    fileHtml = fileHtml.replaceAll("\\{servletPath\\}", SpringBeanUtil.getRequest().getContextPath());
    fileHtml = fileHtml.replaceAll("\\{sessionid\\}", SpringBeanUtil.getSession().getId());
    fileHtml = fileHtml.replaceAll("\\{fieldId\\}", field.getDbField());
    return fileHtml;
  }

  private String getAttachmentList(List<BusinessAttachment> attachments, Integer readOnlyFlag) {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    for (BusinessAttachment attachment : attachments) {
      String divId = "{fieldId}" + i;
      sb.append("<div class='uploadify-queue-item' id='").append(divId).append("'>");
      //非只读,是可以操作,删除
      if(readOnlyFlag !=1 ){
        sb.append("<div class='cancel'><a title='删除' target='ajax' divId='").append(divId).
        append("' onclick='{fieldId}Attachment._deleteFile(this)'>").append("</div>");
        sb.append("<input type='hidden' name='{fieldId}' value='").append(JSONObject.toJSONString(attachment)).append("' />");
      }
      sb.append(
          "<span class='fileName'><a target='dwzExport' href='{servletPath}/manage/common/downloadAttachement?attachmentCode=")
          .append(attachment.getAttachmentCode()).append("&fileName=").append(attachment.getFileName()).append("'>")
          .append(attachment.getFileName());
      sb.append("(").append(attachment.getFileSize() / 1024).append("kb)</a> ");
      sb.append("</span>");
      sb.append("</div>");
      i++;
    }
    return sb.toString();
  }

  /**
   * 
   * <strong>Title : getFileScriptStr<br></strong>
   * <strong>Description : </strong>上传控件需要的js方法
   * <br> 
   * <strong>Create on : 2016-11-28 下午6:15:29<br></strong>
   * <p>
   * @param fileId
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private String getFileScriptStr(int count) {
    StringBuilder sb = new StringBuilder("<script type=\"text/javascript\">");
    sb.append("var {fieldId}Attachment = {");
    //初始化计数
    sb.append("attachmentCount : ").append(count).append(",");
    //uploadSuccess方法开始
    sb.append("uploadSuccess : function(file, data, response) {");
    sb.append("data = eval(\"(\"+data+\")\");");
    sb.append("if(data && data.data){");
    sb.append("var attach = data.data;");
    sb.append("var _id = \"{fieldId}\" + {fieldId}Attachment.attachmentCount;");
    sb.append("var $div = $(\"<div class='uploadify-queue-item'></div>\");");
    sb.append("$div.attr(\"id\", _id);");
    sb.append("$div.append(\"<div class='cancel'><a title='删除' target='ajax' divId='\"+_id+\"' onclick='{fieldId}Attachment._deleteFile(this)'></div>\");");
    sb.append("$div.append(\"<span class='fileName'></span>\");");
    sb.append("var downUrl = hostUrl + \"/common/downloadAttachement?attachmentCode=\" + attach.attachmentCode + \"&fileName=\"+attach.fileName;");
    sb.append("$(\"span:eq(0)\", $div).append(\"<a target='dwzExport' href='\"+downUrl+\"'>\"+attach.fileName+ \"(\"+Math.round(attach.fileSize/1024)+\"KB)</a>\");");
    sb.append("$($div).append(\"<input type='hidden' name='{fieldId}' value='\" +JSON.stringify(data.data)+\"' />\");");
    sb.append("$(\"#div_{fieldId}\", $.pdialog.getCurrent()).append($div);{fieldId}Attachment.attachmentCount ++;}");
    sb.append("},");
    //deleteFile 开始
    sb.append("_deleteFile : function(_this) {");
    sb.append("var _id = $(_this).attr(\"divId\");");
    sb.append("if(_id && _id != null){");
    sb.append("$(\"div#\"+_id).remove();}");
    sb.append("},");
    //uploadFile开始
    sb.append("_uploadFile : function() {");
    sb.append("$('#input_{fieldId}',$.pdialog.getCurrent()).uploadify('upload', '*');}");
    sb.append("}");
    sb.append("</script>");
    return sb.toString();
  }
}
